package com.guigu.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigu.eduservice.entity.Equipment;
import com.guigu.eduservice.entity.EquipmentReservation;
import com.guigu.eduservice.mapper.EquipmentReservationMapper;
import com.guigu.eduservice.service.EquipmentReservationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;



@Service
public class EquipmentReservationImpl extends ServiceImpl<EquipmentReservationMapper, EquipmentReservation> implements EquipmentReservationService {


    @Autowired
    private EquipmentReservationMapper equipmentReservationMapper;
    @Autowired
    private EquipmentServiceImpl equipmentService;

    @Override
    public List<EquipmentReservation> selectAllByUserId(Long userId) {//根据用户ID查询相关设备预定信息
        if (userId == null){
            return new ArrayList<>();
        }
        LambdaQueryWrapper<EquipmentReservation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EquipmentReservation::getUserId, userId);
        List<EquipmentReservation> list = equipmentReservationMapper.selectList(queryWrapper);

        if (list==null){
            return new ArrayList<>();
        }
        // 获取当前时间（标准方式，无需额外依赖！）
        // 由于实体类expireTime是Date类型，这里统一转为Date方便比较
        LocalDateTime currentLocalDateTime = LocalDateTime.now();
        Date currentTime = Date.from(currentLocalDateTime.atZone(ZoneId.systemDefault()).toInstant());


        for (EquipmentReservation  eq:list) {
            //循环拿到设备ID，再根据设备ID查询设备信息
            Equipment equipment = equipmentService.getByIdImageV(eq.getEquipmentId());
            if (equipment != null){
                eq.setEquipment( equipment);
            }
            // 5.2 新增逻辑1：若expireTime为null，自动计算过期时间
            Date expireTime = eq.getExpireTime();
            LocalDateTime createTime = eq.getCreateTime(); // 实体类中是LocalDateTime类型
            Integer reservationPeriod = eq.getReservationPeriod(); // 预定有效期（天）

            // 只有当expireTime为null，且createTime和reservationPeriod都有效时，才计算
            if (expireTime == null && createTime != null && reservationPeriod != null && reservationPeriod > 0) {
                // 计算逻辑：createTime + reservationPeriod天 → 转为Date类型的expireTime
                LocalDateTime expireLocalDateTime = createTime.plusDays(reservationPeriod);
                expireTime = Date.from(expireLocalDateTime.atZone(ZoneId.systemDefault()).toInstant());

                // 更新expireTime到实体（后续判断和数据库更新用）
                eq.setExpireTime(expireTime);
                // 保存计算后的expireTime到数据库（避免下次查询重复计算）
                equipmentReservationMapper.updateById(eq);
            }
            // 5.3 新增逻辑2：判断是否过期并更新状态
            Integer status = eq.getReservationStatus();
            // 跳过已完成/已取消/已过期的状态（2-已转订单，3-已取消，4-已过期），避免重复更新
            if (status != null && (status >= 2 || status == 4)) {
                continue;
            }

            // 核心过期判断：expireTime有效 + 当前时间 > 过期时间
            if (expireTime != null && currentTime.after(expireTime)) {
                eq.setReservationStatus(4); // 更新状态为“已过期”
                equipmentReservationMapper.updateById(eq); // 保存到数据库
                equipment.setStatus(1);//过期就改为已上架
                equipmentService.updateById(equipment);
            }

        }
        return list;
    }
}
